package api

import (
	"animal/octopus/common"
	"animal/octopus/core"
	"net/http"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func GetTopoModuleList(c *gin.Context) {
	log.WithFields(log.Fields{"request": c.Request}).Info(c.Request.URL.Path)

	viewID, err := common.MustGetRequestIntParam(c, "view")
	if err != nil {
		c.PureJSON(http.StatusBadRequest, gin.H{
			"code":   common.ErrInvalidParam,
			"msg":    err.Error(),
			"result": nil,
		})
		log.Error(err)
		return
	}

	if topoModules, err := core.GetTopoModuleList(uint(viewID)); err != nil {
		c.PureJSON(http.StatusInternalServerError, gin.H{
			"code":    1,
			"type":    "failed",
			"message": "failed",
			"result":  nil,
		})
	} else {
		c.PureJSON(http.StatusOK, gin.H{
			"code":    0,
			"type":    "success",
			"message": "success",
			"result": common.GetTopoModuleListResult{
				Modules: topoModules,
			},
		})
	}
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func UpdateTopoModule(c *gin.Context) {
	log.WithFields(log.Fields{"request": c.Request}).Info(c.Request.URL.Path)

	var param common.UpdateTopoModuleParam
	if err := c.ShouldBindJSON(&param); err != nil {
		c.PureJSON(http.StatusBadRequest, gin.H{
			"code":    0,
			"message": "error",
			"result":  nil,
		})
		log.WithField("error", err).Error("invalid request")
		return
	}

	if err := core.UpdateTopoModule(nil, param); err != nil {
		c.PureJSON(http.StatusInternalServerError, gin.H{
			"code":    0,
			"type":    "success",
			"message": "success",
			"result":  nil,
		})
	} else {
		c.PureJSON(http.StatusOK, gin.H{
			"code":    0,
			"type":    "success",
			"message": "success",
			"result":  nil,
		})
	}
}
